<?php 
namespace app\install\controller;
class Index extends Common {

	public function index(){
		if (\Ebcms::isAjax()) {
			if (!\mylib\Input::post('xieyi')) {
				return \mylib\Response::json([
					'code' => 0,
					'message'=>'安装失败！',
					'data' => '不同意安装协议不可安装本软件！'
				]);
			}
			$cfg = [
				'database_type' => 'mysql',
				'database_name' => \mylib\Input::post('name'),
				'server' => \mylib\Input::post('host'),
				'username' => \mylib\Input::post('account'),
				'password' => \mylib\Input::post('password'),
				'prefix' => \mylib\Input::post('prefix'),
				'logging' => true,
				'charset' => 'utf8mb4',
				'option' => [\PDO::ATTR_PERSISTENT=>TRUE, \PDO::ATTR_EMULATE_PREPARES=>FALSE, \PDO::ATTR_ERRMODE=>\PDO::ERRMODE_EXCEPTION]
			];
			try {
				$db = \Ebcms::db($cfg);

			    $sql = file_get_contents(PROJECT_PATH . 'app/install/data/install.sql');
				$sql = str_replace('ebcms_', \mylib\Input::post('prefix'), $sql);
				$sqls = [];
				$sql = explode(";" . PHP_EOL, streol(trim($sql)));
				foreach ($sql as $query) {
				    $tmp = '';
				    $queries = explode(PHP_EOL, trim($query));
				    foreach ($queries as $v) {
				        $tmp .= (isset($v[0]) && $v[0] == '#') || (isset($v[1]) && isset($v[1]) && $v[0] . $v[1] == '--') ? '' : $v;
				    }
				    $sqls[] = $tmp;
				}

				foreach ($sqls as $sql) {
					$db -> query($sql . ';');
				}

				$err = $db -> error();
				if ($err[2]) {
					return \mylib\Response::json([
						'code' => 0,
						'message'=>'安装失败！',
						'data' => $err[2]
					]);
				}
			} catch (\Exception $e) {
				return \mylib\Response::json([
					'code' => 0,
					'message'=>'安装失败！',
					'data' => $e -> getMessage()
				]);
			}

			file_put_contents(PROJECT_PATH . 'config/database.php', '<?php '.PHP_EOL.'return ' . var_export($cfg, true) . ';');
			file_put_contents(PROJECT_PATH . 'config/route.php', file_get_contents(PROJECT_PATH . 'app/install/data/route.php'));

			file_put_contents(PROJECT_PATH . 'app/install.lock', date('Y-m-d H:i:s'));

			\Ebcms::deldir(PROJECT_PATH . 'runtime');
			
			return \mylib\Response::json([
				'code' => 1,
				'message'=>'安装成功！',
				'url'=>\mylib\Route::buildUrl('/admin/index/index')
			]);
		}else{
			$env_err = 0;
			$this->assign('check_env', check_env($env_err));
			$this->assign('check_dirfile', check_dirfile($env_err));
			$this->assign('check_func', check_func($env_err));
			$this -> assign('env_err', $env_err);
			return $this -> html($this -> fetch());
		}
	}
}